// Decompiled by Jad v1.5.7f. Copyright 2000 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   LMSManifestHandler.java

package com.iphaeton.lms.course.scorm12.runtime.core;

import com.iphaeton.exception.PersistenceException;
import com.iphaeton.lms.pojo.course.Course;
import com.iphaeton.lms.pojo.course.Item;
import com.iphaeton.persistence.IPersistenceService;
import java.io.IOException;
import java.io.Serializable;
import java.net.URLDecoder;
import java.util.Vector;
import org.adl.parsers.dom.*;
import org.apache.log4j.Logger;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class LMSManifestHandler extends CPDOMParser
    implements Serializable
{

    public IPersistenceService getHbpservice()
    {
        return hbpservice;
    }

    public void setHbpservice(IPersistenceService hbpservice)
    {
        this.hbpservice = hbpservice;
    }

    public LMSManifestHandler()
    {
        hbpservice = null;
        tempItemList = new Vector();
        items = new Vector();
        courseTitle = "";
        courseDir = "";
        courseID = "";
        control = "";
    }

    public boolean processManifest()
    {
        boolean valid = false;
        logger.debug("Entering LMSManifestHandler::processManifest()");
        try
        {
            parse(sourceToParse);
            logger.debug("Document parsing complete.");
            document = getDocument();
            logger.debug(document);
            valid = true;
            boolean result = processContent();
        }
        catch(SAXException se)
        {
            String message = "Parser threw a SAXException.";
            logger.debug(message);
        }
        catch(IOException ioe)
        {
            String message = "Parser threw a IOException.";
            logger.debug(message);
        }
        logger.debug("Exiting LMSManifestHandler::processManifest()");
        updateDB();
        return valid;
    }

    public boolean processContent()
    {
        logger.debug("*** LMSManifestHandler::processContent() ***");
        boolean result = true;
        if(logger.isDebugEnabled() && document == null)
            logger.debug("the document is null");
        Node contentNode = document.getDocumentElement();
        logger.debug(document);
        logger.debug(contentNode);
        NodeList contentChildren = contentNode.getChildNodes();
        if(logger.isDebugEnabled())
        {
            logger.debug("*** NODE: " + contentNode.getNodeName());
            logger.debug("*** Children - " + contentChildren.getLength() + " ***");
        }
        manifest.fillManifest(contentNode);
        setSequence();
        items = getItemList();
        for(int i = 0; i < contentChildren.getLength(); i++)
        {
            Node currentNode = contentChildren.item(i);
            if(currentNode.getNodeType() != 1 || !currentNode.getNodeName().equalsIgnoreCase("resources"))
                continue;
            logger.debug("*** Found Current Node: " + currentNode.getNodeName());
            result = processResources(currentNode);
            if(!result)
                break;
        }

        if(logger.isDebugEnabled())
        {
            logger.debug("*** Exiting LMSManifestHandler::processContent() ***");
            logger.debug("*** Returning: " + result);
        }
        return result;
    }

    public boolean processResources(Node resourcesNode)
    {
        boolean result = true;
        int level = 1;
        logger.debug("******  LMSManifestHandler:processResources  *********");
        if(document == null)
            logger.debug("the document is null");
        NodeList resourcesChildren = resourcesNode.getChildNodes();
        if(logger.isDebugEnabled())
        {
            logger.debug("*** NODE: " + resourcesNode.getNodeName());
            logger.debug("*** Children - " + resourcesChildren.getLength() + " ***");
        }
        for(int i = 0; i < resourcesChildren.getLength(); i++)
        {
            Node currentNode = resourcesChildren.item(i);
            if(currentNode.getNodeType() != 1 || !currentNode.getNodeName().equalsIgnoreCase("resource"))
                continue;
            logger.debug("*** Found Current Node: " + currentNode.getNodeName());
            result = processResource(currentNode);
            if(!result)
                break;
        }

        if(logger.isDebugEnabled())
        {
            logger.debug("*** Exiting LMSManifestHandler::processResources() ***");
            logger.debug("*** Returning: " + result);
        }
        return result;
    }

    public boolean processResource(Node resourceNode)
    {
        boolean result = true;
        logger.debug("******  LMSManifestHandler:processResource  *********");
        String id = getAttribute(resourceNode, "identifier");
        String scormType = getAttribute(resourceNode, "adlcp:scormtype");
        String type = getAttribute(resourceNode, "type");
        String href = getAttribute(resourceNode, "href");
        updateItemList(id, scormType, type, href);
        if(logger.isDebugEnabled())
        {
            logger.debug("*** Exiting LMSManifestHandler::processResource() ***");
            logger.debug("*** Returning: " + result);
        }
        return result;
    }

    public void updateItemList(String id, String scormType, String type, String href)
    {
        logger.debug("******  LMSManifestHandler:updateItemList  *********");
        ADLItem tempItem = new ADLItem();
        for(int i = 0; i < items.size(); i++)
        {
            tempItem = (ADLItem)items.elementAt(i);
            String idref = tempItem.getIdentifierref();
            if(idref.equals(id))
            {
                if(logger.isDebugEnabled())
                {
                    logger.debug("****** !!  Found Matching Resource  !!  *****");
                    logger.debug("i is:" + i + " -- Items size is" + items.size());
                }
                if(type != null && !type.equals(""))
                    tempItem.setType(type);
                if(scormType != null && !type.equals(""))
                    tempItem.setScormType(scormType);
                if(href != null && !href.equals(""))
                    tempItem.setLaunchLocation(href);
                items.removeElementAt(i);
                items.insertElementAt(tempItem, i);
            }
        }

        logger.debug("****** Exiting - LMSManifestHandler:updateItemList  *********");
    }

    public String getCourseID()
    {
        return courseID;
    }

    public ADLOrganizations getOrgsCopy()
    {
        return manifest.getOrganizations();
    }

    public void setSequence()
    {
        logger.debug("In LMSManifestHandler:setSequence() ");
        logger.debug("Control is: " + control);
    }

    public String getOrganizeId()
    {
        return organizeId;
    }

    public void setOrganizeId(String organizeId)
    {
        this.organizeId = organizeId;
    }

    public void setCourseName(String courseTitle)
    {
        this.courseTitle = courseTitle;
    }

    public void setControl(String controlType)
    {
        control = controlType;
    }

    public void setCreater(String createrId)
    {
        this.createrId = createrId;
    }

    public void setHour(Integer hour)
    {
        this.hour = hour;
    }

    public void setSort(String sort)
    {
        this.sort = sort;
    }

    public void setCriterion(String criterion)
    {
        this.criterion = criterion;
    }

    public void setFileToParse(InputSource inputStream)
    {
        sourceToParse = inputStream;
    }

    public void setComment(String comment)
    {
        this.comment = comment;
    }

    protected void updateDB()
    {
        logger.debug("******  LMSManifestHandler:updateDB()  *********");
        Course course = new Course();
        course.setName(courseTitle);
        course.setControl(control);
        course.setOrganizeId(organizeId);
        course.setState("a");
        course.setCreater(createrId);
        course.setSortId(sort);
        course.setHour(hour);
        course.setCriterion(criterion);
        course.setComment(comment);
        try
        {
            course = (Course)hbpservice.store(course);
            courseID = course.getId();
            logger.info(getClass().getName() + "--\u8BFE\u7A0BID:" + courseID);
        }
        catch(PersistenceException e1)
        {
            e1.printStackTrace();
        }
        ADLItem tempItem = new ADLItem();
        for(int i = 0; i < items.size(); i++)
        {
            tempItem = (ADLItem)items.elementAt(i);
            URLDecoder urlDecoder = new URLDecoder();
            String alteredLocation = new String();
            if(tempItem.getLaunchLocation().startsWith("http://") || tempItem.getLaunchLocation().startsWith("https://"))
                alteredLocation = URLDecoder.decode(tempItem.getLaunchLocation());
            else
                alteredLocation = "E:/temp/CourseImports/" + courseID + "/" + URLDecoder.decode(tempItem.getLaunchLocation());
            Item item = new Item();
            item.setCourseId(course.getId());
            item.setIdentifier(tempItem.getIdentifier());
            item.setFromlms(tempItem.getDataFromLMS());
            item.setLaunch(tempItem.getLaunchLocation());
            item.setLevel(new Integer(tempItem.getLevel()));
            item.setMasteryScore(tempItem.getMasteryScore());
            item.setMaxtime(tempItem.getMaxTimeAllowed());
            item.setParameter(tempItem.getParameterString());
            item.setPrerequisites(tempItem.getPrerequisites());
            item.setSequence(new Integer(i));
            item.setTimelimit(tempItem.getTimeLimitAction());
            item.setTitle(tempItem.getTitle());
            item.setType(tempItem.getScormType());
            item.setSn(tempItem.getSn());
            try
            {
                hbpservice.store(item);
            }
            catch(PersistenceException e)
            {
                e.printStackTrace();
            }
        }

    }

    protected String getAttribute(Node theNode, String theAttribute)
    {
        String returnValue = new String();
        Attr attrs[] = sortAttributes(theNode.getAttributes());
        for(int i = 0; i < attrs.length; i++)
        {
            Attr attribute = attrs[i];
            if(!attribute.getName().equals(theAttribute))
                continue;
            returnValue = attribute.getValue();
            break;
        }

        return returnValue;
    }

    protected Attr[] sortAttributes(NamedNodeMap attrs)
    {
        int len = attrs == null ? 0 : attrs.getLength();
        Attr array[] = new Attr[len];
        for(int i = 0; i < len; i++)
            array[i] = (Attr)attrs.item(i);

        for(int i = 0; i < len - 1; i++)
        {
            String name = array[i].getNodeName();
            int index = i;
            for(int j = i + 1; j < len; j++)
            {
                String curName = array[j].getNodeName();
                if(curName.compareTo(name) < 0)
                {
                    name = curName;
                    index = j;
                }
            }

            if(index != i)
            {
                Attr temp = array[i];
                array[i] = array[index];
                array[index] = temp;
            }
        }

        return array;
    }

    public String getSubElement(Node node, String element)
    {
        String value = new String();
        NodeList kids = node.getChildNodes();
        if(kids != null)
        {
            for(int i = 0; i < kids.getLength(); i++)
                if(kids.item(i).getNodeType() == 1 && kids.item(i).getNodeName().equalsIgnoreCase(element))
                {
                    value = getText(kids.item(i));
                    return value;
                }

        } else
        {
            logger.debug("node has no kids");
        }
        return value;
    }

    public String getText(Node node)
    {
        String value = new String();
        NodeList kids = node.getChildNodes();
        if(kids != null)
        {
            for(int i = 0; i < kids.getLength(); i++)
                if(kids.item(i).getNodeType() == 3 || kids.item(i).getNodeType() == 4)
                    value = value + kids.item(i).getNodeValue().trim();

        } else
        {
            logger.debug("node has no kids");
        }
        return value;
    }

    private static Logger logger;
    protected IPersistenceService hbpservice;
    protected Vector items;
    private Vector tempItemList;
    protected InputSource sourceToParse;
    protected String courseTitle;
    protected String courseDir;
    protected String courseID;
    protected String control;
    protected String organizeId;
    protected String createrId;
    protected String sort;
    protected Integer hour;
    protected String criterion;
    protected String comment;
    static Class class$0; /* synthetic field */

    static 
    {
        logger = Logger.getLogger(com.iphaeton.lms.course.scorm12.runtime.core.LMSManifestHandler.class.getName());
    }
}
